package com.zjmzxfzhl.modules.app.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.zjmzxfzhl.common.core.util.SecurityUtils;
import com.zjmzxfzhl.modules.app.entity.AppDir;
import com.zjmzxfzhl.modules.app.form.DirIsLeafVo;
import com.zjmzxfzhl.modules.sys.entity.vo.ElTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjmzxfzhl.common.core.Result;
import com.zjmzxfzhl.common.core.base.BaseController;
import com.zjmzxfzhl.modules.app.service.AppDirService;

/**
 * Controller
 * 
 * @author 张森荣
 */
@RestController
@RequestMapping("/app/dir")
public class AppDirController extends BaseController {
    @Autowired
    private AppDirService appDirService;

    /**
     * 自定义查询列表
     * 
     * @param appDir
     * @param current
     * @param size
     * @return
     */
//    @PreAuthorize("@elp.single('app:dir:list')")
    @GetMapping(value = "/list")
    public Result list(AppDir appDir, @RequestParam Integer current, @RequestParam Integer size) {
        //查看我创建的目录
        if ("04".equals(appDir.getDirType())) {
            String userId = SecurityUtils.getUserId();
            if (!"admin".equals(userId)) {
                appDir.setCreateBy(userId);
            }
        }
        IPage<AppDir> pageList = appDirService.list(new Page<AppDir>(current, size), appDir);
        return Result.ok(pageList);
    }

//    @PreAuthorize("@elp.single('app:dir:list')")
    @GetMapping(value = "/queryById")
    public Result queryById(@RequestParam String id) {
        AppDir appDir = appDirService.getById(id);
        return Result.ok(appDir);
    }

    /**
     * @功能：新增
     * @param appDir
     * @return
     */
//    @PreAuthorize("@elp.single('app:dir:save')")
    @PostMapping(value = "/save")
    public Result save(@Valid @RequestBody AppDir appDir) {
        if (appDir.getDirType() == null || "".equals(appDir.getDirType())) {
            return Result.error("目录类型不能为空");
        }
        Boolean bool = appDirService.saveAppDir(appDir);
        if (bool == false) {
            return Result.error("添加失败");
        }
        ElTree elTree = appDirService.resultTree(appDir.getDirId());
        return Result.ok(elTree);
    }

    /**
     * @param appDir
     * @return
     * @功能：修改
     */
//    @PreAuthorize("@elp.single('app:dir:update')")
    @PutMapping(value = "/update")
    public Result update(@Valid @RequestBody AppDir appDir) {
        appDir.setParentDirId(null);
        appDir.setDirLevel(null);
        appDir.setDirLevelCode(null);
        appDir.setIsLeaf(null);
        Boolean bool = appDirService.updateById(appDir);
        if (bool == false) {
            return Result.error("修改失败");
        }
        ElTree elTree = appDirService.resultTree(appDir.getDirId());
        return Result.ok(elTree);
    }

    /**
     * @功能：批量删除
     * @param ids
     * @return
     */
//    @PreAuthorize("@elp.single('app:dir:delete')")
    @DeleteMapping(value = "/delete")
    public Result delete(@RequestParam String ids) {
        if (ids == null || ids.trim().length() == 0) {
            return Result.error("ids can't be empty");
        }
        //返回删除对象
        String[] idsArr = ids.split(",");
        List<AppDir> appDirList=new ArrayList<>();
        for (String s:idsArr) {
            AppDir appDir=appDirService.getById(s);
            appDirList.add(appDir);
        }
        Boolean result=appDirService.delByIds(ids);
        if(result==false){
            return Result.error("检查目录下是否存在子目录和未删除文档、项目等！");
        }
        return Result.ok(appDirList);
    }

    /**
     *
     * @param parentId 父节点（无法与分页，查询条件混用）
     * @param level 展开层级（无法与分页，查询条件混用）
     * @param appDir 查询条件
     * @return
     */
//    @PreAuthorize("@elp.single('app:Dir:list')")
    @GetMapping(value = "/getTreeData")
    public Result getSelectTreeData(AppDir appDir,String parentId,Integer level) {
        //查看我创建的目录
        if ("04".equals(appDir.getDirType())) {
            String userId = SecurityUtils.getUserId();
            if (!"admin".equals(userId)) {
                appDir.setCreateBy(userId);
            }
        }
        // 默认返回当前用户数据权限范围的机构树
        Map<String,Object> resultMap=new HashMap();
        List<ElTree> treeData = appDirService.getTreeData(appDir,parentId,level);
        resultMap.put("data",treeData);

        Map<SFunction<AppDir,?>,Object> params=new HashMap<>();
        if(appDir.getDirType()!=null&&!"".equals(appDir.getDirType())){
            params.put(AppDir::getDirType,appDir.getDirType());
        }
        Integer total=appDirService.count(new LambdaQueryWrapper<AppDir>().allEq(params));
        resultMap.put("total",total);

        return Result.ok(resultMap);
    }

    /**
     * @功能：移动树
     * @param id 节点id
     * @param parentId 原父id
     * @param newParentId 目标父id
     * @return
     */
//    @PreAuthorize("@elp.single('app:Dir:update')")
    @PutMapping(value = "/moveTree")
    public Result moveTree(@RequestParam String id,@RequestParam String parentId,@RequestParam String newParentId) {
        AppDir appDir=appDirService.getById(id);
        if(appDir==null){
            return Result.error("未找到结点");
        }
        appDir.setParentDirId(newParentId);
        appDirService.moveTree(appDir,parentId);
        ElTree elTree = appDirService.resultTree(appDir.getDirId());
        return Result.ok(elTree);
    }

    /**
     * 查询类型目录数量
     *
     * @return
     */
//    @PreAuthorize("@elp.single('app:dir:list')")
    @GetMapping(value = "/dirIsLeaf")
    public Result dirIsLeaf() {
        List<DirIsLeafVo> dirIsLeafVos= appDirService.dirIsLeaf();
        return Result.ok(dirIsLeafVos);
    }
}
